/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * author Svetlana Shikhutskaya
 */

var marker;
var state;
var directionsDisplay;
var geocoder;
var map;
var userAddress;
var warehouses;
var duration;
var direction;
var distance;
var cost;

function initialized() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(50.27, 30.30);
    var mapOptions = {
        zoom: 9,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    directionsDisplay.setMap(map);
    loadWarehouses();
    checkAddress();
}
            
function authInitialized(){
    initialized();
    getUserAddress();
    document.getElementById("u_address").value=userAddress;
}   

function getUserAddress(){
    $.post('MapView',function(responseText) { 
        UserAddress=responseText;
    })
}
            
function calculate(warehouse){
    //    alert('calc');
    var request = {
        origin: userAddress,
        destination: warehouse.address,
        travelMode: google.maps.TravelMode.DRIVING
    };
    var directionsService=new google.maps.DirectionsService();
    directionsService.route(request, function(result, status){
        if(status==google.maps.DirectionsStatus.OK){
            distance=result.routes[0].legs[0].distance.value;
//            console.log(result.routes[0]);
            direction=result;
            var meters = distance % 1000;
            var kilometers = ~~(distance/1000);
            document.getElementById("distance").value=kilometers+" km "+meters+" m";
           // duration=~~(distance/warehouse.koeff);
           duration=(kilometers/warehouse.koeff).toFixed(2);
            cost=(kilometers*warehouse.rate).toFixed(2);
            document.getElementById("cost").value=cost;
            document.getElementById("duration").value=duration;
            document.getElementById("amount-pay").value=parseInt(document.getElementById("tot-price").value)+
            parseInt(document.getElementById("cost").value);
        }
        else {
            document.getElementById('route_error').innerHTML="Sorry, we couldn't draw a route and calculate your shipping price";
        }
    });
}
            
function loadWarehouses(){
    $.post('MapView',function(responseText) { 
        warehouses=$.parseJSON(responseText);
//        console.log(warehouses);
        codeWarehouses(warehouses);
        fill();
    })                        
}
            
function codeWarehouses(list){
    $.each(list, function(index, value){
        code(value);
    })
}
            
function deleteMarker(temp){
    if(temp==1 && marker!=null){
        marker.setMap(null);
    }
}
function drawCustomMarker(){
    var pinColor = "#FE7569";
    var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
        new google.maps.Size(21, 34),
        new google.maps.Point(0,0),
        new google.maps.Point(10, 34));
    var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
        new google.maps.Size(40, 37),
        new google.maps.Point(0, 0),
        new google.maps.Point(12, 35));
    marker.setIcon("http://maps.google.com/mapfiles/ms/icons/yellow-dot.png");
    marker.setShadow(pinShadow);
}
            
function code(address,temp){
    var addr;
    if(temp!=1){
        addr=address.address;
    }
    else{
        addr=address;
    }
    //    alert(addr);
    geocoder.geocode({
        'address':addr
    },function(results, status){
        state=status;
        deleteMarker(temp);
        if (status==google.maps.GeocoderStatus.OK){
            marker=new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            })
            if(temp!=1)
                marker=null;
            if(temp==1){
                drawCustomMarker();
            }
            map.setCenter(results[0].geometry.location);
        }
        else {
        //            alert("Geocode was not successful for the following reason: " + status);
        }
    })
}

function codeUserAddress() {
    var address = document.getElementById("address").value;
    if(address!=""){
        code(address,1);
        userAddress=address;
        calculate(warehouses[0]);
    }
}


function checkAddress(){
    document.getElementById('route_error').innerHTML='';
    var address = document.getElementById("address").value;
    if(address==''){
        document.getElementById('draw-user-marker').disabled=true;
        document.getElementById('draw-route').disabled=true;
        document.getElementById('warehouses').disabled=true;
        document.getElementById("distance").value='';
        document.getElementById("cost").value='';
    }
    else{
        document.getElementById('draw-user-marker').disabled=false;
        document.getElementById('warehouses').disabled=false;
        document.getElementById('draw-route').disabled=false;
    }
}

function fill(){
    var sel = document.getElementById('warehouses');
    for (var i = 0; i < warehouses.length; i++){
        var newOpt = new Option(warehouses[i].name,warehouses[i].id);
        sel.options.add(newOpt);
    }
}

function displayDistance(){
    for (var i=0;i<warehouses.length;i++){
        if (document.getElementById("warehouses").value==warehouses[i].id){
            calculate(warehouses[i]);
        }
    }
};

function drawRoute(){
    for (var i=0;i<warehouses.length;i++){
        if (document.getElementById("warehouses").value==warehouses[i].id){
            //            alert(warehouses[i]['address']);
            directionsDisplay.setDirections(direction);
        //            console.log(warehouses);
        }
    }
}
